#include "stdafx.h"

#include "Defines.h"
#include "ScopedHandle.h"

String PathAppend (const String& aPath, const String& aElement)
{
    String Result = aPath;
    if (Result[Result.size () - 1] != TEXT('\\')) {
        Result += TEXT('\\');
    }

    return Result + aElement;
}

String CreateGuid ()
{
    UUID Item;
    UuidCreate (&Item);

    RPC_CSTR Text;
    UuidToString (&Item, &Text);

    String Result = reinterpret_cast<_TCHAR*> (Text);
    RpcStringFree (&Text);

    return Result;
}

int EnumerateFiles (const String& aPattern, FileFound aHandler)
{
    WIN32_FIND_DATA Data;
    TCHAR Root[8] = {0};
    TCHAR Directory[MAX_PATH] = {0};
    TCHAR FileName[MAX_PATH] = {0};
    int Result = 0;

    _tsplitpath(aPattern.c_str (), Root, Directory, FileName, 0);
    ScopedHandle Search = FindFirstFile(aPattern.c_str (), &Data);
    bool Stop = false;
    if (Search() != INVALID_HANDLE_VALUE) {
        do {
            if ((Data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {
                String FullPath = PathAppend(Root, PathAppend(Directory, Data.cFileName));
                Stop = aHandler (FullPath);
                ++Result;
            }
        } while (!Stop && FindNextFile(Search (), &Data));
    }

    return Result;
}

bool FileExists(const String& aFullPath)
{
    ScopedHandle Check = CreateFile(aFullPath.c_str(), GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
    DWORD Error = GetLastError();
    return (Error == ERROR_SUCCESS) || (Error == ERROR_ACCESS_DENIED);
}
